import { onMounted, onUnmounted, ref } from "vue";
import { throttle } from "underscore";

export default function useScroll(elRef) {
  let el = window
  const isReachBottom = ref(false);

  const clientHeight = ref(0);
  const scrollHeight = ref(0);
  const scrollTop = ref(0);

  //监听window窗口的滚动/throttle:节流
  const scrollListenerHandler = throttle(() => {
    if(el === window){
      clientHeight.value = document.documentElement.clientHeight;
      scrollTop.value = document.documentElement.scrollTop;
      scrollHeight.value = document.documentElement.scrollHeight;
    }else{
      clientHeight.value = el.clientHeight 
      scrollHeight.value = el.scrollHeight
      scrollTop.value = el.scrollTop 
    }

    // 判断是否到底 scrollHeight:元素总高度 scrollTop:向下移的高度 clientHeight:能看见的高度
    if (scrollHeight.value <= scrollTop.value + clientHeight.value) {
      isReachBottom.value = true;
    }
  }, 100);

  onMounted(() => {
    if(elRef) el = elRef.value
    el.addEventListener("scroll", scrollListenerHandler);
  });

  onUnmounted(() => {
    el.removeEventListener("scroll", scrollListenerHandler);
  });

  return { isReachBottom, clientHeight, scrollHeight, scrollTop };
}
